Group Anagrams

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],

Return:

  1. [
  2. ["ate", "eat","tea"],
  3. ["nat","tan"],
  4. ["bat"]
  5. ]

Note: All inputs will be in lower-case.

Solution:

  1. public class Solution {
  2. public List<String> anagrams(String[] strs) {
  3. List<String> res = new ArrayList<String>();
  4. if (strs == null) {
  5. return res;
  6. }
  7. Map<String, List<String>> map = new HashMap<String, List<String>>();
  8. for (int i = 0; i < strs.length; i++) {
  9. String str = strs[i];
  10. String key = sort(str);
  11. List<String> list = map.containsKey(key) ? map.get(key) : new ArrayList<String>();
  12. list.add(str);
  13. map.put(key, list);
  14. }
  15. for (Map.Entry<String, List<String>> entry : map.entrySet()) {
  16. String key = entry.getKey();
  17. List<String> list = entry.getValue();
  18. if (list.size() > 1) {
  19. res.addAll(list);
  20. }
  21. }
  22. return res;
  23. }
  24. String sort(String str) {
  25. char[] chars = str.toCharArray();
  26. Arrays.sort(chars);
  27. return new String(chars);
  28. }
  29. }